package wo.common.util;

import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;

import com.sun.javadoc.FieldDoc;
import com.sun.javadoc.RootDoc;

/**
 * 读取本项目中类对应的Java文件注释.
 * @author cailei
 * @date Nov 4, 2018
 */
public class WoJavaDocUtil {
	
	private final static Logger LOG = LogManager.getLogger(WoJavaDocUtil.class);
	
	private static RootDoc root;
    
	/**
	 * @return
	 */
	public static String getClassComment () {
		LOG.info("getClassComment of " + root.classes()[0].name() + ":" + root.classes()[0].commentText());
		return root.classes()[0].commentText();
	}
	
	/**
	 * @param fieldName
	 * @return
	 */
	public static String getFieldComment (String fieldName) {
		for (FieldDoc f : root.classes()[0].fields(false)) {
			if (f.name().equals(fieldName)) {
				LOG.info("getFieldComment of " + f.name() + ":" + f.commentText());
				return f.commentText();
			}
		}
		return null;
	}
	
	private static String srcPath = "./src/main/java/";
	
	public static void setSrcPath (String src) {
		srcPath = src;
	}
	
    public static RootDoc read (String entityClass) {
    	String javaFile = srcPath + entityClass.replace('.', '/') + ".java";
    	LOG.info(javaFile);
    	// LOG.info(Column.class.getResource("/"));
    	// 调用com.sun.tools.javadoc.Main执行javadoc
        // javadoc的调用参数
        // -doclet 指定自己的docLet类名
        // -classpath 参数指定 源码文件及依赖库的class位置，不提供也可以执行，但无法获取到完整的注释信息(比如annotation)
        // -encoding 指定源码文件的编码格式
        com.sun.tools.javadoc.Main.execute(new String[] {
        	"-doclet", Doclet.class.getName(), 
		// 因为自定义的Doclet类并不在外部jar中，就在当前类中，所以这里不需要指定-docletpath 参数，
		//  "-docletpath", Doclet.class.getResource("/").getPath(),
            "-encoding","utf-8",
        // "-classpath", "/root/mavenrepo/org/hibernate/javax/persistence/hibernate-jpa-2.1-api/1.0.0.Final/hibernate-jpa-2.1-api-1.0.0.Final.jar",
        // 获取单个代码文件.java的javadoc
            javaFile
        });
        return root;
    }
    
    /**
     * 一个简单Doclet,收到 RootDoc对象保存起来供后续使用
     * @author cailei
     * @date Nov 4, 2018
     */
    public static  class Doclet {

        public static boolean start(RootDoc root) {
            WoJavaDocUtil.root = root;
            return true;
        }
    }
    
    public static void main(final String ... args) throws Exception{
    	RootDoc root = read ("wo.common.util.WoJavaDocUtil");
    	LOG.info(root.classes()[0].commentText());
    }
}
